﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

namespace ResourceManager
{
    /// <summary>
    /// 版本控制器
    /// </summary>
    class VersionController
    {
        /// <summary>
        /// 加载版本列表文件
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool LoadVersionFile(string filename)
        {
             _xmlRoot = XElement.Load(filename);
            _isVerionFileLoaded = true;
            return true;
        }

        public bool IsLoaded
        {
            get
            {
                return _isVerionFileLoaded;
            }
        }

        /// <summary>
        /// 验证资源在本地是否为最新版本
        /// </summary>
        /// <param name="localPath">文件路径</param>
        /// <param name="resourceName">资源名</param>
        /// <returns>true表示最新版，false表示不是</returns>
        public bool VerifyVersion(string resourceName)
        {
            if (!File.Exists(Config.Instance.LocalPath + resourceName))
            {
                return false;
            }

            string localMD5 = GetFileMD5(Config.Instance.LocalPath + resourceName);
            if (null == localMD5)
            {
                return false;
            }

            var elements = from e in _xmlRoot.Elements("file")
                           where e.Attribute("name").Value == resourceName 
                           select e;


            /// 找到MD5不匹配，则认为资源不为最新;
            /// 如果找不到MD5，则认为资源为最新
            foreach (XElement e in elements)
            {
                string remoteMD5 = e.Attribute("md5").Value;
                if (remoteMD5 != localMD5)
                {
                    return false;
                }
            }
            return true; 
        }

        /// <summary>
        /// 获取本地文件的MD5值
        /// </summary>
        /// <param name="filename">文件全路径名</param>
        /// <returns>文件MD5</returns>
        public static string GetFileMD5(string filename)
        {
            try
            {
                FileStream file_stream = new FileStream(filename, FileMode.Open);
                System.Security.Cryptography.HashAlgorithm hashAlgo = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] md5 = hashAlgo.ComputeHash(file_stream);
                file_stream.Close();
                StringBuilder sb = new StringBuilder();
                foreach (byte tmp in md5)
                {
                    sb.Append(tmp.ToString("X2"));
                }
                return sb.ToString();
            }
            catch (System.Exception)
            {
                return null;
            }
        }

        private XElement _xmlRoot;

        /// <summary>资源版本文件是否已经初始化</summary>
        private bool _isVerionFileLoaded = true; 
    }
}
